<?php

namespace User;

use C\L\WebUserController;
use C\M\UserAddress;

class AddressController extends WebUserController
{
    protected function init()
    {
        $this->service = $this->s_user_address;

        $this->pubSearchKeys = [
            'is_default',
        ];

        $this->hideKeys = [
            'is_delete'
        ];

        $this->timeToDateKeys = [
            'uptime', 'addtime'
        ];

        // $this->pubSearchKeys = [
        //     'type', 'stype'
        // ];
        
        $this->updateKeys = [
            'name', 'tel', 'province', 'city', 'county', 'address', 'postal_code',
            'is_default', 'tags', 'tag', 'area_code'
        ];
    }

    public function addAction()
    {
        $uid = $this->uid;
        $lockKey = "uid:$uid:address:lock";
        if (!$this->di['s_user']->lock($lockKey, 5)) {
            $this->error('服务器繁忙，请稍后重试');
        }
        $add = [];
        $add['uid'] = $uid;
        $add['name'] = $name = $this->getValue('name', true, 'string');
        $add['tel'] = $tel = $this->getValue('tel', true, 'string');
        $add['area_code'] = $area_code = $this->getValue('area_code', false) ?? null;
        $add['province'] = $province = $this->getValue('province', true, 'string');
        $add['city'] = $city = $this->getValue('city', true, 'string');
        $add['county'] = $county = $this->getValue('county', true, 'string');
        $add['address'] = $address = $this->getValue('address', true, 'string');
        $add['postal_code'] = $postal_code = $this->getValue('postal_code', false, 'int');
        $add['is_default'] = $is_default = $this->getValue('is_default', false) ?? 'N';
        if (!preg_match('/^(1(([356789][0-9])|(47)))\d{8}$/', $tel)) {
            $this->error();
        }
        if ($this->s_user_address->save($add)) {
            $this->success();
        }
        $this->error('添加失败');
    }

    public function beforeSearch()
    {
        $uid = $this->uid;
        $this->params['data']['uid'] = $uid;
        return true;
    }

    public function beforeUpdate(&$data)
    {
        $uid = $this->uid;
        $id = $this->getValue('id', true);
        if (!$this->s_user_address->search(['uid' => $uid, 'id' => $id])) {
            $this->error('无此地址');
        }
        return true;
    }

    public function defaultAction()
    {
        $uid = $this->uid;

        $result = UserAddress::findFirst([
            "uid = '".$uid."' and is_delete = 0",
            "order" => "is_default DESC, id ASC",
        ]);

        $this->success($result);
    }
}
